// console.log("脚本执行开始");
$NG.AllReady(function (
	page,
	{
		useValuesChange,
		useClick,
		useUpdateRow,
		useUpdateRows,
		useDataIndexChange,
		useBeforeClick,
	}
) {
	// console.log("脚本执行进入");
	var mstform = $NG.getCmpApi("p_form_pro_accounts_pay_m");
	var dgrid = $NG.getCmpApi("p_form_pro_accounts_pay_d1"); //获取表体数据
	var dgrid1 = $NG.getCmpApi("p_form_invoice_information"); //获取表体数据
	var dgrid4 = $NG.getCmpApi("p_form_pro_accounts_pay_d3")
	var dgrid2 = $NG.getCmpApi("p_form_pro_accounts_pay_d2")
	var ArrType = []
	const gridToolbar = $NG.getCmpApi("toolbar_p_form_pro_accounts_pay_d1");
	gridToolbar.getItem("imp").setProps({ children: "引用采购入库/采购退货" });

	const gridToolbar1 = $NG.getCmpApi("toolbar_p_form_pro_accounts_pay_d2");
	gridToolbar1.getItem("imp").setProps({ children: "引用采购罚款单" });

	const billno = $NG
		.getCmpApi("p_form_pro_accounts_pay_m")
		.getItem("bill_no")
		.getValue();

		if (page.oType == 'add') {
		console.log(222222222222222);
		setTimeout(() => {
			getHtxx()
			$NG.execServer(
				"getCntMInfoByPhid",
				{ phid: mstform.getItem("u_cnt_name").getValue() },
				function (res) {
					// console.log(JSON.parse(res.data)[0].extendObjects, "res.data");
					let datas = JSON.parse(res.data)[0].extendObjects;
					$NG.updateState((updater) => {
						updater.data.p_form_pro_accounts_pay_m.setProps({
							u_rece_bank: {
								value: datas.tick_taxbankid,
								label: datas.tick_taxbankname,
							},
							u_bank_no: datas.tick_taxaccountno,
							u_supplier_phid: {
								value: datas.supply_id,
								label: datas.supply_name,
							},
							u_cnt_amt: datas.cnt_sum_vat_fc,
							u_rece_bank: datas.inv_taxaccountno,
							u_payee: {
								value: datas.supply_id,
								label: datas.supply_name,
							},
							u_cnt_phid: datas.pcm_no,
						});
					});
				}
			);
		}, 300);
		mstform.getItem('u_zfdsyje').setValue(0)
		$NG.updateState((updater) => {
			updater.data.p_form_pro_accounts_pay_m.setProps({
				u_yftzbl: 1
			})
		})
		$NG.updateState((updater) => {
			updater.data.p_form_pro_accounts_pay_m.setProps({
				u_invoice_all_amt: 0,
				u_remarks: '无',
				phid_org: {
					value: '',
					label:'',
				},
			});
		});
		$NG.updateState((updater) => {
			updater.data.p_form_pro_accounts_pay_m.setProps({
				u_ljkp_amt:0
			});
		});

	}
	let user = $NG.getUser();
	useDataIndexChange(({ args }) => {
		const [record] = args;		
		record.isTaxAmtManual = true; // 标记为手动修改
		dgrid.refreshView();
	}, "u_tax_amt"); 
	async function getToken() {
		const token = await $NG.request.post({
			url: "http://nginx.clouddev.hisense.com/sd/sdToFi/fiIntegration/authenticationFi",
			header: {
				"Content-Type": "application/json",
			},
		});
		// console.log("获取 token 成功:", token);
		return token;
	}

	async function getEventCode() {
		console.log(JSON.stringify({ bill_no: billno }));
		
		const eventCode = await $NG.request.post({
			url: "http://nginx.clouddev.hisense.com/sd/sdToFi/fiIntegration/getCGEventCode",
			// url: "https://inner-apisix.hisense.com/hisense/sd/Fi/sdToFi/fiIntegration/getCGEventCode?user_key=pxgy9hyt9udfgfcsbzizykw0xfqi6uk6",
			data: JSON.stringify({ bill_no: billno }),
			header: {
				"Content-Type": "application/json",
			},
		});
		console.log(eventCode);
		// console.log("获取 eventCode 成功:", eventCode);
		return eventCode;
	}

	$NG.getCmpApi("toolbar_p_form_invoice_information").insert({
		id: "sendBtn",
		text: "上传发票信息",
		iconCls: "icon-New",
	});

	useClick(async function ({ args }) {
		// console.log("点击了获取发票信息按钮");
		// $NG.getCmpApi("toolbar_top").getItem("save").getRef().click(); //点击获取发票的时候，保存单据
		const identifytype = billno; // 页面唯一标识（根据实际需求设置）
		const token = await getToken();
		const eventCode = await getEventCode();

		// 修正 WebSocket URL
		const socketUrl = "wss://fi-uat.hisense.com/ierp/msgwatch/";

		// 初始化 WebSocket
		const socket = new WebSocket(
			`${socketUrl}?identifytype=${encodeURIComponent(
				identifytype
			)}&token=${encodeURIComponent(token)}&listenerType=RimWebSocketListener`
		);

		// WebSocket 打开事件
		socket.onopen = () => {
			// console.log("WebSocket 连接已建立:", new Date());
			var url = "https://fi-uat.hisense.com/ierp/";
			var viewfpUrl =
				url + "index.html?formId=rim_fpzs_main&eventCode=" + eventCode;
			var encodeUrl = encodeURIComponent(viewfpUrl, "utf-8");
			var requestUrl =
				url +
				"accessTokenLogin.do?encode=true&access_token=" +
				token +
				"&redirect=" +
				encodeUrl;
			window.open(requestUrl);
			socket.send("来自客户端的消息: " + location.href + " - " + new Date());
		};

		// WebSocket 收到消息事件
		socket.onmessage = (event) => {
			// console.log("收到服务器消息:", event.data); // 输出服务器返回的消息
			const data = JSON.parse(event.data);
			const invoiceData = data.invoiceData;

			// 获取表体当前的所有行数据
			const existingRows = $NG
				.getCmpApi("p_form_invoice_information")
				.getRows();

			// 创建一个Set，用于快速判断表体中是否存在某发票号
			const existingInvoiceNos = new Set(
				existingRows.map((row) => row.u_invoiceno)
			);

			// 定义存储新数据的数组
			var gridArr = [];

			// 判断 invoiceData 是否存在，并获取长度
			const gridCount = invoiceData ? invoiceData.length : 0;
			if (gridCount > 0) {
				for (let i = 0; i < gridCount; i++) {
					const invoice = invoiceData[i];
					const invoice_item = invoice.items[0];

					// 判断发票号是否已存在于表体中
					if (existingInvoiceNos.has(invoice.invoiceNo)) {
						continue; // 跳过重复数据
					}

					// 如果发票号未重复，则加入到gridArr中
					var gridObj = {
						u_invoicetype: invoice.invoiceType,
						u_serialno: invoice.serialNo,
						u_invoicecode: invoice.invoiceCode,
						u_invoiceno: invoice.invoiceNo,
						u_invoicedate: invoice.invoiceDate,
						u_checkcode: invoice.checkCode,
						u_salername: invoice.salerName,
						u_salertaxno: invoice.salerTaxNo,
						u_saleraddressphone: invoice.salerAddressPhone,
						u_saleraccount: invoice.salerAccount,
						u_buyername: invoice.buyerName,
						u_buyertaxNo: invoice.buyerTaxNo,
						u_buyeraddressPhone: invoice.buyerAddressPhone,
						u_buyeraccount: invoice.buyerAccount,
						u_invoiceamount: invoice.invoiceAmount,
						u_totaltaxamount: invoice.totalTaxAmount,
						u_totalamount: invoice.totalAmount,
						u_remark: invoice.remark,
						u_machineno: invoice.machineNo,
						u_drawer: invoice.drawer,
						u_reviewer: invoice.reviewer,
						u_payee: invoice.payee,
						u_invoicestatus: invoice.invoiceStatus,
						u_expendstatus: invoice.expendStatus,
						u_billcreatetime: invoice.billCreateTime,
						u_checkstatus: invoice.checkStatus,
						u_invaliddate: invoice.invalidDate,
						u_type: invoice.type,
						u_originalinvoicecode: invoice.originalInvoiceCode,
						u_originalinvoiceno: invoice.originalInvoiceNo,
						u_downloadurl: invoice.downloadUrl,
						u_filetype: invoice.fileType,
						u_isrevise: invoice.isRevise,
						u_snapshoturl: invoice.snapshotUrl,
						u_errcode: invoice.errcode,
						u_description: invoice.description,
						u_validatemessage: invoice.validateMessage,
						u_msg: invoice.msg,
						u_name: invoice.name,
						u_configType: invoice.configType,
						u_config: invoice.config,
						u_key: invoice.key,
						u_taxrate: invoice_item.taxRate,
						u_goodscode: invoice_item.u_goodscode,
						u_goodsname: invoice_item.goodsName,
					};
					gridArr.push(gridObj);
				}

				// 如果有新数据，插入到表体中
				if (gridArr.length > 0) {
					dgrid1.addRows(gridArr);
					// console.log("新增的数据:", gridArr);
				} else {
					// console.log("没有需要插入的新数据。");
				}
			} else {
				// console.log("没有发票数据！");
			}
		};

		// WebSocket 关闭事件
		socket.onclose = (event) => {
			// console.log("WebSocket 连接已关闭:", new Date());
			if (event.code !== 1000) {
				// 非正常关闭
				console.error(
					"连接异常关闭，错误代码:",
					event.code,
					"原因:",
					event.reason
				);
			}
		};

		// WebSocket 错误事件
		socket.onerror = (error) => {
			console.error("WebSocket 错误:", error);
		};

		// 防止内存泄漏，组件卸载时关闭 WebSocket
		return () => {
			if (socket.readyState === WebSocket.OPEN) {
				socket.close();
			}
		};
	}, "sendBtn");

	if ($NG.getCmpApi("p_form_pro_accounts_pay_m")) {
		if (mstform.getItem("u_business_type").getValue() == 1) {
			$NG.updateUI((updater, value) => {
				updater.fieldSetForm.p_form_pro_accounts_pay_m.u_ywfp.setProps({
					disable: true,
				});
			});
			// mstform.setHidden("u_ywfp"); //设置隐藏
		} else {
			$NG.updateUI((updater, value) => {
				updater.fieldSetForm.p_form_pro_accounts_pay_m.u_ywfp.setProps({
					disable: false,
				});
			});
			// mstform.setHidden("u_ywfp", false); //设置隐藏
		}
		/**
		 *@default: 初始化
		 */
		getPtInfoByPhid();
		cntMFilter();

		if (user) {
			$NG.updateState((updater) => {
				updater.data.p_form_pro_accounts_pay_m.setProps({
					u_pay_org: {
						value: user.orgID,
						label: user.orgName,
					},
				});
			});
		}
	}

	if (page.oType == "add") {
		dgrid.updateRow(dgrid.getRows());
	}
	// if (mstform.getItem("u_cnt_name").getValue()) {
	// 	try {
	// 		$NG.execServer(
	// 			"getCumulateAmt",
	// 			{ cnt_phid: mstform.getItem("u_cnt_name").getValue(), status: 1 },
	// 			function (res) {
	// 				const data = JSON.parse(res.data)[0].extendObjects;
	// 				// console.log(data, "累计金额");
	// 				$NG.updateState((updater) => {
	// 					updater.data.p_form_pro_accounts_pay_m.setProps({
	// 						u_acc_pay_amt: data.total_pay_amount ?? 0,
	// 						u_ljkp_amt: data.u_invoice_all_amt_total ?? 0
	// 					});
	// 				});
	// 			}
	// 		);
	// 	} catch (error) { }
	// }

	/**
	 *@license://表头字段变化逻辑END	//表头字段变化逻辑BEGIN
	 */
	useValuesChange(({ args }) => {
		console.log(`项目监听测试`);
		mstform.getItem("u_cnt_name").setValue("");
		getHtxx()
		getPtInfoByPhid();
		cntMFilter();
		getPhidPcJgdt()
		getGsNsAppStatusDt()
	}, "p_form_pro_accounts_pay_m.phid_pc");

	function getHtxx() {
		if (mstform.getItem("phid_pc").getValue()) {
			$NG.execServer(
				"GETxs_cnt",
				{ pc: mstform.getItem("phid_pc").getValue() },
				function (res) {
					const datas = JSON.parse(res.data)[0].extendObjects;
					console.log(datas);
					
					//帮助字段赋值
					$NG.updateState((updater) => {
						updater.data.p_form_pro_accounts_pay_m.setProps({
							u_sxht_name: {
								//事业部or组织
								value: datas.phid,
								label: datas.bill_name,
							},
						});
					});
				}
			);
		}
	}
	useValuesChange(({ args }) => {
		setYftz()
		dgrid.getRows().forEach(item => {			
			computedV1(item, true)
		})
		if (window.isGiveLock) {
			clearTimeout(window.isGiveLock)
		}
		window.isGiveLock = setTimeout(() => {
			isPayGive()
		}, 1500)
		dgrid.refreshView()
	}, "p_form_pro_accounts_pay_m.u_yftzbl")
	
	useValuesChange(({ args }) => {
		if (mstform.getItem("u_business_type").getValue() == 1) {
			$NG.updateUI((updater, value) => {
				updater.fieldSetForm.p_form_pro_accounts_pay_m.u_ywfp.setProps({
					disable: true,
				});
			});
			// mstform.setHidden("u_ywfp"); //设置隐藏
		} else {
			$NG.updateUI((updater, value) => {
				updater.fieldSetForm.p_form_pro_accounts_pay_m.u_ywfp.setProps({
					disable: false,
				});
			});
			// mstform.setHidden("u_ywfp", false); //设置隐藏
		}
		// console.log(args, "u_business_type");
	}, "p_form_pro_accounts_pay_m.u_business_type");
	/**
	 *@license:监听服务于工程表 1.累计分包金额
	 */

	useDataIndexChange(({ args }) => {
		const [record] = args;
		record.isTaxAmtManual = false;
		computedV1(args[0], true)
	}, "u_yftzbl")

	useDataIndexChange(({ args }) => {
		const [record] = args;
		record.isTaxAmtManual = false;
		computedV1(args[0], false, true)
	}, "u_qty")

	useUpdateRows(({ args }) => {
		let rows = args[0];
		rows.forEach(async (record, index) => {
			// console.log(record, index, "record");
			if (!record.u_yftzbl) {
				record.u_yftzbl = mstform.getItem("u_yftzbl").getValue()
			}
			if (record.u_yfsl == undefined || record.u_yfsl == null) {
				record.u_yfsl = record.u_qty
			}
			if (!record.u_souce_id) return;
			$NG.execServer(
				"SourceIdFlag",
				{ phid: record.u_souce_id },
				function (res) {
					try {
						if (JSON.parse(res.data)[0].extendObjects?.user_if_fixasset == 1) {
							$NG.execServer(
								"searchCountToSourceId",
								{ sourceid: record.u_souce_id },
								function (res) {
									if (JSON.parse(res.data)[0].extendObjects.row_count == 0) {
										$NG.alert(
											`物料名称: ${record.u_item_no} 物料编码: ${record.u_item_name_EXName} 该物料未创建资产卡片`
										);
									}
								}
							);
						}
					} catch (error) { }
				}
			);
		});
		dgrid.refreshView()
	}, "p_form_pro_accounts_pay_d1");
	/**
	 *@function:带出项目信息
	 */
	function getPtInfoByPhid() {
		if (mstform.getItem("phid_pc").getValue()) {
			$NG.execServer(
				"getPtInfoByPhid",
				{ phid: mstform.getItem("phid_pc").getValue() },
				function (res) {
					const datas = JSON.parse(res.data)[0].extendObjects;
					//帮助字段赋值

					$NG.updateState((updater) => {
						updater.data.p_form_pro_accounts_pay_m.setProps({
							// u_supply_att: datas.u_supply_att, //计划完工日期
							// u_supply_name: datas.u_supply_name, //计划竣工日期
							u_pc_no: datas.pc_no, //项目编码
							u_division: {
								//事业部or组织
								value: datas.division_phid,
								label: datas.division_name,
							},
							u_regional_center: {
								//区域中心
								value: datas.regional_center_phid,
								label: datas.regional_center_name,
							},
							u_product_line: {
								//产品线
								value: datas.midwife_phid,
								label: datas.midwife_name,
							},
							phid_org: {
								value: datas.org_phid,
								label: datas.org_name,
							},
						});
					});
				}
			);
		}
	}
	/**
	 *@function:过滤项目
	 */
	function cntMFilter() {
		$NG.updateUI((updater, state) => {
			// console.log(updater);
			updater.fieldSetForm.p_form_pro_accounts_pay_m.u_pay_type.setProps({
				onBeforeOpen: async () => {
					var u_cnt_name = $NG
						.getCmpApi("p_form_pro_accounts_pay_m")
						.getItem("u_cnt_name")
						.getValue();
					if (!u_cnt_name) {
						$NG.alert("请先选择合同");
						return false;
					} else {
						return true;
					}
				}
			});
		});
		$NG.updateUI((updater, state) => {
			// console.log(updater);
			updater.fieldSetForm.p_form_pro_accounts_pay_m.u_cnt_name.setProps({
				onBeforeOpen: async () => {
					var phid_pc = $NG
						.getCmpApi("p_form_pro_accounts_pay_m")
						.getItem("phid_pc")
						.getValue();

					if (!phid_pc) {
						$NG.alert("请先选择项目");
						return false;
					} else {
						return true;
					}
				},
				...(!!$NG
					.getCmpApi("p_form_pro_accounts_pay_m")
					.getItem("phid_pc")
					.getValue() && {
					clientSqlFilter: {
						bill_type: 7,
						phid_pc: $NG
							.getCmpApi("p_form_pro_accounts_pay_m")
							.getItem("phid_pc")
							.getValue(),
					},
				}),
			});
		});

		// mstform.setReadOnly("u_cnt_name", false); //取消只读
		// $NG.updateUI((updater, value) => {
		// 	updater.fieldSetForm.p_form_pro_accounts_pay_m.u_cnt_name.setProps({
		// 		required: false,
		// 	});
		// });

		$NG.execServer(
			"getCntCount",
			{ phid_pc: mstform.getItem("phid_pc").getValue(), type: 7 },
			function (res) {
				try {
					let Num = JSON.parse(res.data).length;
					if (Num != 1) return; //如果大于1个，则不自动填充

					const datas = JSON.parse(res.data)[0].extendObjects;

					$NG.updateState((updater) => {
						updater.data.p_form_pro_accounts_pay_m.setProps({
							u_cnt_name: {
								value: datas.phid,
								label: datas.bill_name,
							},
						});
					});
					$NG.execServer(
						"getCntMInfoByPhid",
						{ phid: datas.phid },
						function (res) {
							// console.log(JSON.parse(res.data)[0].extendObjects, "res.data");
							let datas = JSON.parse(res.data)[0].extendObjects;
							$NG.updateState((updater) => {
								updater.data.p_form_pro_accounts_pay_m.setProps({
									u_rece_bank: {
										value: datas.tick_taxbankid,
										label: datas.tick_taxbankname,
									},
									u_bank_no: datas.tick_taxaccountno,
									u_supplier_phid: {
										value: datas.supply_id,
										label: datas.supply_name,
									},
									u_cnt_amt: datas.cnt_sum_vat_fc,
									u_rece_bank: datas.inv_taxaccountno,
									u_payee: {
										value: datas.supply_id,
										label: datas.supply_name,
									},
									u_cnt_phid: datas.pcm_no,
								});
							});
						}
					);
					// mstform.setReadOnly("u_cnt_name"); //设置只读
					$NG.updateUI((updater, value) => {
						updater.fieldSetForm.p_form_pro_accounts_pay_m.u_cnt_name.setProps({
							required: true,
						});
					});
                    setTimeout(()=>{
                        getCntPayDetailInfo()
                        getJfdInfo()
                    },300)
				} catch (error) { }
			}
		);
	}
	/**
	 *@license:带出订单编号
	 */
	useValuesChange(({ args }) => {
		// console.log("是否进入");
		$NG.execServer(
			"getCntMInfoByPhid",
			{ phid: mstform.getItem("u_cnt_name").getValue() },
			function (res) {
				// console.log(JSON.parse(res.data)[0].extendObjects, "res.data");
				let datas = JSON.parse(res.data)[0].extendObjects;
				$NG.updateState((updater) => {
					updater.data.p_form_pro_accounts_pay_m.setProps({
						u_rece_bank: {
							value: datas.tick_taxbankid,
							label: datas.tick_taxbankname,
						},
						u_bank_no: datas.tick_taxaccountno,
						u_supplier_phid: {
							value: datas.supply_id,
							label: datas.supply_name,
						},
						u_cnt_amt: datas.cnt_sum_vat_fc,
						u_rece_bank: datas.inv_taxaccountno,
						u_payee: {
							value: datas.supply_id,
							label: datas.supply_name,
						},
						u_cnt_phid: datas.pcm_no,
					});
				});
			}
		);
		$NG.execServer(
			"getCumulateAmt",
			{ cnt_phid: args[0].u_cnt_name.origin.phid, status: 1 },
			function (res) {
				try {
					const data = JSON.parse(res.data)[0].extendObjects;
					// console.log(data, "累计金额2222222222222222");
					$NG.updateState((updater) => {
						updater.data.p_form_pro_accounts_pay_m.setProps({
							u_acc_pay_amt: data.total_pay_amount ?? 0,
							u_ljkp_amt: data.u_invoice_all_amt_total ?? 0
						});
					});
				} catch (error) { }
			}
		);
		$NG.execServer(
			"searchCntZ",
			{ phid: args[0].u_cnt_name.origin.phid },
			function (res) {
				try {
					const data = JSON.parse(res.data);
					let newData = data.map(item => item.extendObjects)
					ArrType = newData
					const TypeArray = newData.map(item => item.phid_item.toString());
					$NG.updateUI((updater) => {
						const fields = ["u_pay_type"];
						fields.forEach((field) => {
							// $NG.getPageUI(); 根据组件目录设置路径，可能存在 PCFieldSetPanelGroup[i][field]
							updater.fieldSetForm.p_form_pro_accounts_pay_m[field].setProps({
								// hidden: true, //隐藏
								// required: true, //必输
								// disabled: true, //只读
								clientSqlFilter: `phid in (${TypeArray.join(',')})`, //过滤条件
								// placeholder: "请选择", //输入框字段加提示语
								// data: newArray, //下拉过滤
							});
						});
					});

					$NG.updateUI((updater, state) => {
						// console.log(updater);
						updater.fieldSetForm.p_form_pro_accounts_pay_m.u_pay_type.setProps({
							onBeforeOpen: async () => {
								var u_cnt_name = $NG
									.getCmpApi("p_form_pro_accounts_pay_m")
									.getItem("u_cnt_name")
									.getValue();
								if (!u_cnt_name) {
									$NG.alert("请先选择合同");
									return false;
								} else {
									return true;
								}
							},
							...(!!$NG
								.getCmpApi("p_form_pro_accounts_pay_m")
								.getItem("u_cnt_name")
								.getValue() && {
								clientSqlFilter: `phid in (${TypeArray.join(',')})`, //过滤条件
							}),
						});
					});
					// console.log(newArray, "newDatacaigouyingfu");
				} catch (error) { }
			}
		);
		getCntPayDetailInfo()
		getJfdInfo()
	}, "p_form_pro_accounts_pay_m.u_cnt_name");
	/**
	 *@license:带出订单编号
	 */
	useValuesChange(({ args }) => {
		// console.log(args[0].u_pay_type.value, 'u_pay_type')
		if (args[0].u_pay_type.value) {
			const obj = ArrType.find(item => item.phid_item == args[0].u_pay_type.value)
			// console.log(obj?.user_zq, "obj.user_zq")
			if (obj.user_zq) {
				// console.log(addDaysToDate(obj.user_zq), 'addDaysToDate(obj.user_zq)')
				mstform.getItem("u_yfykp").setValue(addDaysToDate(obj.user_zq))
			}
		}
		// console.log(ArrType, 'arrtype')


	}, "p_form_pro_accounts_pay_m.u_pay_type");

	useUpdateRow(({ args, table }) => {
		const item = args[0];
		computed(item);
		// console.log('useUpdateRow');
		
		// computedV1(item);
		dgrid.refreshView();
		// console.log(item, "监听表格");
		bqSumAmt()
	}, "p_form_pro_accounts_pay_d1");

	useUpdateRows(({ args, table }) => {
		//监听物料明细表单
		if (window.isGiveLock) {
			clearTimeout(window.isGiveLock)
		}
		window.isGiveLock = setTimeout(() => {
			isPayGive()
		}, 1500)
		let total = 0;
		args[0].forEach((item) => {
			computed(item);
			computedV1(item);
			total += item.u_amt_vat;
		});
		// console.log(total, "total监听物料明细表单");

		$NG.updateState((updater) => {
			updater.data.p_form_pro_accounts_pay_m.setProps({
				u_inventory_amt: total,

			});
		});

		bqSumAmt()
		reduceUPurPayAmt()
		dgrid.refreshView();
	}, "p_form_pro_accounts_pay_d1");

	useUpdateRows(({ args, table }) => {
		//监听罚款明细表单
		reduceUPurPayAmt()
		bqSumAmt()
		dgrid.refreshView();
	}, "p_form_pro_accounts_pay_d2");


	function reduceUPurPayAmt() {
		const amt = dgrid.getRows().reduce((value, item) => {
			value += (Number(item.u_amt_vat) || 0)
			return value
		}, 0)
		const fk = dgrid2.getRows().reduce((value, item) => {
			value += (Number(item.u_fk_amt) || 0)
			return value
		}, 0)
		console.log(`表头金额计算`, amt, fk);
		$NG.updateState((updater) => {
			updater.data.p_form_pro_accounts_pay_m.setProps({
				u_fk_ant: fk,
				u_pur_pay_amt: (Number(amt - fk) || 0),
				// u_zfdsyje: (Number(amt - fk) || 0)
			});
		});
		if (page.oType == 'add'||page.oType == 'edit') {
			$NG.updateState((updater) => {
				updater.data.p_form_pro_accounts_pay_m.setProps({
					u_zfdsyje: (Number(amt - fk) || 0)
				});
			});
			
		}
	}

	let timeLock = 0
	function bqSumAmt() {
		//禁用
		return
		// if (timeLock) {
		// 	clearTimeout(timeLock)
		// }
		// timeLock = setTimeout(() => {
		// 	$NG.updateState((updater) => {
		// 		updater.data.p_form_pro_accounts_pay_m.setProps({
		// 			u_pur_pay_amt: (Number(mstform.getItem("u_invoice_all_amt").getValue()) || 0) - (Number(mstform.getItem("u_fk_ant").getValue()) || 0)
		// 		});
		// 	});
		// }, 300)
	}
	useUpdateRows(({ args, table }) => {
		let total = 0;
		args[0].forEach((item) => {
			total = item.u_totalamount;
		});
		// console.log(total, "total发票明细表单");
		$NG.updateState((updater) => {
			updater.data.p_form_pro_accounts_pay_m.setProps({
				u_invoice_all_amt: total,
			});
		});
		dgrid.refreshView();
		bqSumAmt()
	}, "p_form_invoice_information");

	// 获取合同款项
	getCntPayDetailInfo()
	function getCntPayDetailInfo() {
		const cnt = mstform.getItem("u_cnt_name").getValue()
		if (!cnt) return
		$NG.execServer("getCntPayDetailInfo", { cnt }, (res) => {
            console.log(`获取合同条款`,res);
			const _data = JSON.parse(res.data).reduce((value, item) => {
				const el = item.extendObjects
				value.push({
					u_fklx: el.namephid,
					u_fklx_EXName: el.name_new,
					u_zfbl: el.bal_percent,
					u_amt: el.bal_amt_fc,
					u_fktj: el.user_fktj,
					u_zfjsjs: el.user_zfjsjs,
					u_zffs: el.user_zffs,
					u_zq_dt: el.user_xzzq,
                    user_zbqs_dt: el.user_zbqs_dt
				})
				return value
			}, [])
			// console.log(`获取合同条款`,_data);
			window._catchPayType = [..._data]
		})


	}

	// 应付调整比率
	function setYftz() {
		const arr = dgrid.getRows()
		arr.forEach(item => {
			item.u_yftzbl = mstform.getItem("u_yftzbl").getValue()
		})
		dgrid.refreshView()
	}

	function computed(item) {
		$NG.execServer(
			"getItemInfoZZCP",
			{ phid: item.u_item_name },
			function (res) {
				try {
					const datas = JSON.parse(res.data)[0].extendObjects;
					item.u_item_no = datas.code;
					item.u_wl_type = datas.phid_resbs;
					item.u_wl_type_EXName = datas.name;
					item.u_spec = datas.spec;
					item.u_unit = datas.phid_unit;
					item.u_unit_EXName = datas.msname;
					dgrid.refreshView();
				} catch (error) { }
			}
		);
	}
	var tabPanel = document.getElementsByClassName("ant-tabs-tab"); //获取所有tab页元素
	tabPanel[1].addEventListener("click", function () {
		// console.log("tab2被点击了");
		setTimeout(() => {
			if (page.oType == "add") {
				$NG.getCmpApi("toolbar_top").getItem("save").getRef().click(); //点击获取发票的时候，保存单据
				$NG.alert("请先保存主表数据");
				tabPanel[0].click();
			}
		}, 200);
	});
	if ("ant-tabs-tab-active")
		useClick(async function ({ args }) {
			// console.log(args, "useClick");
			//按钮点击事件
			return false;
		}, "save");
	useBeforeClick(async function ({ args }) {
		//按钮点击前事件
		// console.log(args, "useBeforeClick");
	}, "save");


	// 获取将罚单信息
	page.oType == 'add' && getJfdInfo()
	function getJfdInfo() {
		const cnt = mstform.getItem("u_cnt_name").getValue()
		if (!cnt) return
		$NG.execServer("getJfdInfo", { cnt }, (res) => {
			console.log(`奖罚单信息`,res);
			if (res.count == 0) return
			dgrid2.clearRows().then(()=>{
                dgrid2.addRows(JSON.parse(res.data).reduce((value, item) => {
                    const el = item.extendObjects
                    value.push({
                        u_fkdbh: el.bill_no,
                        u_fk_amt: el.u_fk_amt,
                        u_fkdt: el.bill_dt,
                        u_fksy: el.u_fksy,
                        u_zfbl: el.user_zffs,
                        u_souce_id: el.dphid,
                        u_souce_table: el.mphid
                    })
                    return value
                }, []))
            })
		})

	}


	function computedV1(rowItem, bool, qtylock) {
		const record = rowItem;

		if (typeof record.isTaxAmtManual === "undefined") {
			record.isTaxAmtManual = false;
		}
		let u_qty = null
		let u_yftzbl = null
		if (bool) {
			u_qty = Math.floor((Number(record.u_yfsl) || 0) * (Number(record.u_yftzbl) || 0)) // 数量，默认为 0
		} else {
			u_qty = (Number(record.u_qty) || 0) // 数量，默认为 0
		}
		if (qtylock) {
			u_yftzbl = (((Number(record.u_qty) || 0)) / (Number(record.u_yfsl) || 0)).toFixed(4)
		} else {
			u_yftzbl = (Number(record.u_yftzbl) || 0)
		}
		// 提供默认值并确保为数字类型，防止字符串影响计算
		const u_prc_vat = Number(record.u_prc_vat) || 0; // 含税单价，默认为 0
		const u_tax_rate = Number(record.u_tax_rate) || 0; // 税率，默认为 0

		// 计算不含税单价
		const u_prc = u_prc_vat / (1 + u_tax_rate);
		console.log(record.isTaxAmtManual);
		
		// 计算字段值
		const u_amt_vat = u_qty * u_prc_vat; // 价税合计
		// const u_tax_amt = u_amt_vat - u_qty * u_prc; // 税额
		const u_yyfpje = u_amt_vat
		if (!record.isTaxAmtManual) {
			const u_tax_amt = u_amt_vat - u_qty * u_prc;
			record.u_tax_amt = u_tax_amt; // 自动计算
		}
		const u_amt = u_amt_vat - (record.u_tax_amt || 0);
		// 更新 record 对象
		Object.assign(record, {
			u_prc,
			u_amt_vat,
			u_amt,
			u_yftzbl,
			// u_tax_amt,
			u_yyfpje,
			u_qty,
			user_yfd_rest_qty: u_qty,
		});
		dgrid.refreshView()
	}

	function computedV3(total1, total2) {

		//如果他们是数字
		if (typeof total1 === "number" && typeof total2 === "number") {
			return total1 - total2;
		}
	}
    const alertLock = {
        xmjgLock : true,
        gsnsLock:true,
        zbLock:true
    }
	// 付款类型条件判断
	function isPayGive() {
		// 确认付款单数量
		const payForm = dgrid.getRows().reduce((value, item) => {
			const arr = value.filter(el => {
				if (el.u_rkdjh == item.u_rkdjh) {
					return el
				}
			})
			// console.log(`arr`,arr);
			if (value.length == 0) {
				value.push({ ...item })
			} else {
				if (arr.length == 0) {
					value.push({ ...item })
				}
			}

			return value
		}, [])
		console.log(`付款单数量`,payForm);
		// 大批条件判断
		const arr = window._catchPayType.reduce((value, item) => {
			payForm.forEach(pay => {
				const _map = { ...item }
				const total_amt = dgrid.getRows().reduce((value, item) => {
					if (item.u_rkdjh == pay.u_rkdjh) {
						value += (Number(item.u_init_amt_vat) || 0)
					}
					return value
				}, 0)
				_map.u_amt = total_amt * (Number(item.u_zfbl) || 0)
				switch ((Number(_map.u_fklx) || 0)) {
					case 8570000000000008: // 设备到货
						_map.u_zq_dt = data1Indate2(pay.u_rudspsj, item.u_zq_dt)
						break;
					case 8570000000000005: // 安装调试
						_map.u_zq_dt = data1Indate2(pay.u_atsj, item.u_zq_dt)
						break;
					case 8570000000000004: //验收款
						switch ((Number(_map.u_fktj) || 0)) {
							case 5: //项目经理确认验收完成款
								_map.u_zq_dt = data1Indate2(pay.u_yssj, item.u_zq_dt, item.user_zbqs_dt)
								break
							case 4: //项目整体验收完成款
								if (!window._catch_PhidPc_jgdt && alertLock.xmjgLock) {
                                    alertLock.xmjgLock = false
                                    _map.u_zq_dt = undefined
									$NG.alert("当前项目终验竣工时间为空！")
									_map.u_zq_dt = null
								} else {
									_map.u_zq_dt = data1Indate2(window._catch_PhidPc_jgdt, item.u_zq_dt)
								}
								break
                            default:
                                _map.u_zq_dt = undefined
						}
						break
					case 8570000000000006://审计款
						if (!window._catch_GsAppdt && alertLock.gsnsLock) {
                            alertLock.gsnsLock = false
							$NG.alert("当前公司内审审核时间为空")
							break
						}
						_map.u_zq_dt = data1Indate2(window._catch_GsAppdt, item.u_zq_dt)
						break
					case 8570000000000007:// 质保金
						switch ((Number(_map.u_fktj) || 0)) {
							case 7:
								_map.u_zq_dt = data1Indate2(pay.u_rudspsj, item.u_zq_dt)
								break
							case 8:
								_map.u_zq_dt = data1Indate2(pay.u_yssj, item.u_zq_dt)
								break
							case 9:
								if (!window._catch_PhidPc_zbdqdt && alertLock.zbLock) {
                                    alertLock.zbLock = false
                                    _map.u_zq_dt = undefined
									$NG.alert("当前项目质保到期时间为空")
									break
								}
								_map.u_zq_dt = window._catch_PhidPc_zbdqdt
								break
                            default:
                                _map.u_zq_dt = undefined
                                break

						}
						break
					case 8570000000000001:
						_map.u_zq_dt = undefined
						// console.log(`测试中~~~~`);
						break;
				}
				// console.log(_map.u_zq_dt);
				if (_map.u_zq_dt && _map.u_zq_dt.includes("NaN")) {
					_map.u_zq_dt = undefined
				}
				value.push({ ..._map })
			})
			return value
		}, [])
		// console.log(`添加数据`,arr);
		dgrid4.clearRows().then(() => {
            // 设置优先级  预付款、设备到货、安装调试款、验收款、质保金、审计款
            const temp = {
                "质保金":5,
                "验收款":4,
                "预付款":1,
                "设备到货":2,
                "安装调试款":3,
                "审计款":6
            }
            
			dgrid4.addRows([...arr.sort((a,b)=>temp[a.u_fklx_EXName] - temp[b.u_fklx_EXName])])
		})
	}

	// 时间相加
	function data1Indate2(date1, day, year) {
		if (!date1) {
			date1 = undefined
            return ""
		}
		const date = new Date(date1).getTime()
		const dayLong = (Number(day) || 0) * 24 * 60 * 60 * 1000
		const dateFinal = new Date(date + dayLong)
		return `${dateFinal.getFullYear() + (Number(year) || 0)}-${String(dateFinal.getMonth() + 1).padStart(2, '0')}-${String(dateFinal.getDate()).padStart(2, '0')}`
	}
	//获取项目终验竣工时间按
	getPhidPcJgdt()
	function getPhidPcJgdt() {
		const phid_pc = mstform.getItem("phid_pc").getValue()
		if (!phid_pc) return
		$NG.execServer("getPhidPcJgdt", { phid_pc }, (res) => {
			if (res.count == 0) return
			window._catch_PhidPc_jgdt = JSON.parse(res.data)[0].extendObjects.u_finial_dt
			window._catch_PhidPc_zbdqdt = JSON.parse(res.data)[0].extendObjects.u_warranty_dt
		})
	}
	// 获取公司内审送审时间
	getGsNsAppStatusDt()
	function getGsNsAppStatusDt() {
		const phid_pc = mstform.getItem("phid_pc").getValue()
		if (!phid_pc) return
		$NG.execServer("getGsNsAppStatusDt", { phid_pc }, (res) => {
			if (res.count == 0) return
			window._catch_GsAppdt = JSON.parse(res.data)[0].extendObjects.app_dt
		})
	}
});

// 输出示例：2024-12-05

// getItemInfoZZCP; 物料查询sql使用
function addDaysToDate(days) {
	// 获取当前日期
	const currentDate = new Date();

	// 将天数转换为毫秒数
	const millisecondsPerDay = 24 * 60 * 60 * 1000;
	const totalMilliseconds = days * millisecondsPerDay;

	// 计算新日期的毫秒数
	const newDateMilliseconds = currentDate.getTime() + totalMilliseconds;

	// 创建新的 Date 对象
	const newDate = new Date(newDateMilliseconds);

	// 格式化日期
	const year = newDate.getFullYear();
	const month = String(newDate.getMonth() + 1).padStart(2, '0');
	const day = String(newDate.getDate()).padStart(2, '0');

	return `${year}-${month}-${day}`;
}

